/*! ******************************************************************************
 *
 * Pentaho Data Integration
 *
 * Copyright (C) 2002-2017 by Hitachi Vantara : http://www.pentaho.com
 *
 *******************************************************************************
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 ******************************************************************************/

package org.pentaho.di.ui.core.dialog;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.*;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.*;
import org.pentaho.di.core.Const;
import org.pentaho.di.repository.Repository;
import org.pentaho.di.ui.core.PropsUI;
import org.pentaho.di.ui.core.gui.GUIResource;
import org.pentaho.di.ui.core.gui.WindowProperty;
import org.pentaho.di.ui.trans.step.BaseStepDialog;


/**
 * Dialog to display an error generated by a Kettle Exception.
 *
 * @author Matt
 * @since 19-06-2003
 */
public class FileOpenErrorDialog extends Dialog {
  private static Class<?> PKG = FileOpenErrorDialog.class; // for i18n purposes, needed by Translator2!!

  Object transJobMeta;
  String type;
  Repository rep;

  private Label wlDesc;
  private Text wDesc;
  private FormData fdlDesc, fdDesc;

  private Button wOpen, wOpenWithConf, wCancel;

  private Shell shell;
  private SelectionAdapter lsDef;
  private PropsUI props;

  private boolean cancelled;

  private boolean overWrite;


  public FileOpenErrorDialog(Object meta, String type, Repository rep, Shell parent, String title, String message, java.util.List<String> contents ) {
    super( parent, SWT.NONE );
    this.transJobMeta = meta;
    this.type = type;
    this.rep = rep;
    showErrorDialog( parent, title, message,contents);
  }


  private void showErrorDialog( Shell parent, String title, String message, java.util.List<String> contents) {
    if ( parent.isDisposed() ) {
      return;
    }
    this.props = PropsUI.getInstance();

    Display display = parent.getDisplay();
    final Font largeFont = GUIResource.getInstance().getFontBold();
    final Color gray = GUIResource.getInstance().getColorDemoGray();

    shell =
      new Shell( parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MAX | SWT.MIN | SWT.APPLICATION_MODAL | SWT.SHEET );
    props.setLook( shell );
    shell.setImage( GUIResource.getInstance().getImageShowErrorLines() );

    FormLayout formLayout = new FormLayout();
    formLayout.marginWidth = Const.FORM_MARGIN;
    formLayout.marginHeight = Const.FORM_MARGIN;

    shell.setLayout( formLayout );
    shell.setText( title );

    int margin = Const.MARGIN;

    // From step line
    wlDesc = new Label( shell, SWT.NONE );
    wlDesc.setText( message );
    props.setLook( wlDesc );
    fdlDesc = new FormData();
    fdlDesc.left = new FormAttachment( 0, 0 );
    fdlDesc.top = new FormAttachment( 0, margin );
    wlDesc.setLayoutData( fdlDesc );
    wlDesc.setFont( largeFont );

    wDesc = new Text( shell, SWT.MULTI | SWT.LEFT | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL );

    final StringBuilder text = new StringBuilder();
    text.append("若继续打开，打开的转换在不经过修改并保持将会覆盖资源库中的数据源配置，这将可能会引起其他转换运行出错！");
    for(String dbName:contents){
      text.append(System.getProperty("line.separator"));
      text.append( dbName );
    }
    wDesc.setText( text.toString() );

    wDesc.setBackground( gray );
    fdDesc = new FormData();
    fdDesc.left = new FormAttachment( 0, 0 );
    fdDesc.top = new FormAttachment( wlDesc, margin );
    fdDesc.right = new FormAttachment( 100, 0 );
    fdDesc.bottom = new FormAttachment( 100, -50 );
    wDesc.setLayoutData( fdDesc );
    wDesc.setEditable( false );

    wOpen = new Button( shell, SWT.PUSH );
    wOpen.setText( "继续打开" );
    wOpenWithConf = new Button( shell, SWT.PUSH );
    wOpenWithConf.setText( "保留转换配置并打开" );
    wCancel = new Button( shell, SWT.PUSH );
    wCancel.setText( "取消打开" );

    Button[] buttons = new Button[] { wOpen, wOpenWithConf, wCancel, };

    BaseStepDialog.positionBottomButtons( shell, buttons, margin, null );

    // Add listeners
    wOpen.addListener( SWT.Selection, new Listener() {
      public void handleEvent( Event e ) {
        ok(true);
      }
    } );
    wCancel.addListener( SWT.Selection, new Listener() {
      public void handleEvent( Event e ) {
        cancel();
      }
    } );
    wOpenWithConf.addListener( SWT.Selection, new Listener() {
      public void handleEvent( Event e ) {
//        showOpenWithConf();
        ok(false);
      }
    } );

    lsDef = new SelectionAdapter() {
      public void widgetDefaultSelected( SelectionEvent e ) {
        ok(true);
      }
    };
    wDesc.addSelectionListener( lsDef );

    // Detect [X] or ALT-F4 or something that kills this window...
    shell.addShellListener( new ShellAdapter() {
      public void shellClosed( ShellEvent e ) {
        ok(true);
      }
    } );
    // Clean up used resources!
    shell.addDisposeListener( new DisposeListener() {
      public void widgetDisposed( DisposeEvent arg0 ) {
      }
    } );

    BaseStepDialog.setSize( shell );

    // Set the focus on the "OK" button
    wOpen.setFocus();

    shell.open();
    while ( !shell.isDisposed() ) {
      if ( !display.readAndDispatch() ) {
        display.sleep();
      }
    }
  }

//  protected void showOpenWithConf(  ) {
//    BaseMessageDialog dialog =
//      new BaseMessageDialog( shell, "警告", "打开的转换在不经过修改并保持将会覆盖资源库中的数据源配置，这将可能会引起其他转换运行出错！");
//    dialog.open();
//  }

  public void dispose() {
    props.setScreen( new WindowProperty( shell ) );
    shell.dispose();
  }

  private void ok(boolean over){
    overWrite = over;
//    try {
//      // 更新加载转换的数据库信息
//      if(type.equals("trans")){
//        ((TransMeta) transJobMeta).fixDbInfo(rep);
//      }else{
//        ((JobMeta) transJobMeta).fixDbInfo(rep);
//      }
//    } catch (KettleException e) {
//      LogUtil.error("数据库信息处理出现异常：[{0}]"+e);
//    }
    dispose();
  }

  private void cancel() {
    cancelled = true;
    dispose();
  }

  public boolean isCancelled() {
    return cancelled;
  }

  public boolean isOverWrite() {
    return overWrite;
  }
}
